import Dep from "./dep";

export class Observer {
    constructor(value) {
        this.value = value;
        //新增ob属性，表明已转换Observer实例
        //def(value,"_ob_",this);
        if (Array.isArray(value)) {
            //...
        } else {
            this.walk(value);
        }
    }
    walk(obj) {
            let objArr = obj.keys();
            for (let i = 0; i < objArr.length; i++) {
                defineReactive(obj, obj[i]);
            }
        }
        //将对象转换成可观测对象
    defineReactive(obj, key, val) {
        if (arguments.length == 2) {
            val = obj[key]
        }
        if (typeof obj == 'Object') {
            new Observer(obj);
        }
        const dep = new Dep();
        Object.defineProperty(obj, key, {
            enumerable: true,
            configurable: true,
            //属性读取 //get中收集依赖
            get() {
                dep.addSub();
                return val;
            },
            //属性修改 // set中通知依赖更新
            set(newVal) {
                if (val === newVal) {
                    return;
                }
                val = newVal;
                dep.updatedSub();
            }
        })
    }
}